#include "YujcListener.h"
#include <process.h>

YujcListener::YujcListener(string name, string pass, PrintMessageToChat printMsg, AddUserToList addUsr)
{
	putStringToChatWindow = printMsg;
	addUserToComboBox = addUsr;

	JID jid;
	jid.setServer("yuriss");
	jid.setUsername(name);
	j = new Client( jid, pass );
	j->registerConnectionListener( this );
	j->rosterManager()->registerRosterListener( this );
}

YujcListener::~YujcListener(void)
{
	j->disconnect();
	delete j;
	delete chat_room;
}

void YujcListener::connect(ThreadHandler thread)
{
	j->connect(false);
	_beginthread( thread, 0, j );
}

void YujcListener::handleRoster( const Roster& roster )
{
	Roster::const_iterator it = roster.begin();
	for( ; it != roster.end(); ++it )
	{
		users.push_back((*it).second->jid().c_str());
		if(addUserToComboBox != NULL)
			(* addUserToComboBox)((*it).second->jid().c_str(), (*it).second->name().c_str());
	}
}

void YujcListener::onConnect()
{
	JID roomJID( "chat@conference.yuriss/" + this->j->jid());
	chat_room = new MUCRoom( this->j, roomJID, 0, 0 );
	chat_room->join();
}

void YujcListener::onDisconnect( ConnectionError e )
{
	char * text = "Error connection: ";
	char * zag = "ERROR ";	
	MessageBoxA(GetActiveWindow(), (LPCSTR)text , (LPCSTR)zag, MB_ICONERROR );
}

string YujcListener::getUserJIDByIndex(int index)
{
	return users.at(index);
}
